﻿using Antlr.Runtime.Misc;
using Common;
using DBUtility;
using DeliveryManage;
using DeliveryManage.Controllers;
using DeliveryManage.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing.Printing;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Web;
using System.Web.Http.Results;
using System.Web.Mvc;
using System.Web.UI.WebControls;
using static Common.DTEnums;

namespace CallRobotManage.Controllers
{
    public class OrderController : BaseController
    {
        protected int totalCount;
        protected int page;
        protected int pageSize;
        #region 返回新闻每页数量=========================
        private int GetPageSize(int _default_size, string CookieName)
        {
            int _pagesize;
            if (int.TryParse(Utils.GetCookie(CookieName, "FxManage"), out _pagesize))
            {
                if (_pagesize > 0)
                {
                    return _pagesize;
                }
            }
            return _default_size;
        }
        #endregion

        #region 订单列表
        // 所有订单
        public ActionResult OrderList()
        {
            ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 200, msg = "允许执行该操作的权限，操作成功！" };
            if (!ChkAdminLevels("OrderList", DTEnums.ActionEnum.View.ToString()))
            {
                ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 400, msg = "您没有执行该操作的权限，操作失败！" };
                return View();
            }; //检查权限
            #region 搜索
            DeliveryManage.Model.Sys_User user = Session["session_admin_info"] as DeliveryManage.Model.Sys_User;
            this.pageSize = GetPageSize(DTRequest.GetQueryInt("pageSize", 10), "pageSize");
            this.page = DTRequest.GetQueryInt("page", 1);

            ViewData["pageSize"] = this.pageSize;
            ViewData["page"] = this.page;
            string keywords = DTRequest.GetQueryString("keywords").Trim();
            int status = DTRequest.GetQueryInt("status", -1);
            string where = "";
            DeliveryManage.DAL.Sys_UserRelation userRelationDal = new DeliveryManage.DAL.Sys_UserRelation();
            string myLower= userRelationDal.GetMyLowerList(user.Id);
            where += string.Format(" EmployeeId in({0})", myLower);
            if (!string.IsNullOrEmpty(keywords))
            {
                //模糊查询
                if (keywords.IndexOf("*") >= 0)//判断字符串中是否包含字符串*号
                {
                    where += string.Format(" and (OrderNo like '{0}' or CustomerName like '{0}' or CustomerTel like '{0}')", keywords.Replace("*", "%"));
                }
                else
                {
                    where += string.Format(" and (OrderNo like '%{0}%' or CustomerName like '%{0}%' or CustomerTel like '%{0}%')", keywords);
                }
                ViewBag.Keyword = keywords;
            }
            if (status > -1) 
            {
                where += string.Format(" and Status={0}", status);
            }
            #endregion
            List<DeliveryManage.Model.Pro_Orders> list = new List<DeliveryManage.Model.Pro_Orders>();
            DeliveryManage.DAL.Pro_Orders dal = new DeliveryManage.DAL.Pro_Orders();
            list = dal.GetQueryList(this.pageSize, this.page, where, "Id Desc", out this.totalCount);
            ViewBag.OrderList = list;
            //绑定页码
            string pageUrl = Utils.CombUrlTxt("/Order/OrderList", "page={0}&pageSize={1}&keywords={2}&status={3}", "__id__", pageSize.ToString(), keywords.ToString(), status.ToString());
            ViewBag.PageInnerHtml = Utils.OutPageList(this.pageSize, this.page, this.totalCount, pageUrl, 8);

            #region 物流方式
            ListItemCollection wayitem = new ListItemCollection();
            wayitem.Add(new ListItem("请选择发货方式...", "-1"));
            wayitem.Add(new ListItem("京东", "0"));
            wayitem.Add(new ListItem("散酒", "1"));
            wayitem.Add(new ListItem("存酒", "2"));
            wayitem.Add(new ListItem("自提", "3"));

            ViewData["DeliveryWayList"] = new SelectList(wayitem, "value", "text");

            Dictionary<int, string> dicDeliveryWay = new Dictionary<int, string>();
            dicDeliveryWay.Add(0, "京东");
            dicDeliveryWay.Add(1, "散酒");
            dicDeliveryWay.Add(2, "存酒");
            dicDeliveryWay.Add(3, "自提");
            ViewData["dicDeliveryWay"] = dicDeliveryWay;
            #endregion

            #region 订单状态

            List<EnumEntity> enumList = DTEnums.EnumToList<DTEnums.EnumOrderState>();
            ListItemCollection Statusitem = new ListItemCollection();
            Statusitem.Add(new ListItem("全部...", "-1"));
            Dictionary<int, string> dicStatus = new Dictionary<int, string>();
            foreach (var item in enumList)
            {
                Statusitem.Add(new ListItem(item.Describe, item.PrameKey.ToString()));
                dicStatus.Add(item.PrameKey, item.Describe);
            }
            ViewData["StatusList"] = new SelectList(Statusitem, "value", "text");
            ViewData["dicStatus"] = dicStatus;

            #endregion

            return View();
        }
        #endregion

        #region 创建订单
        //创建订单
        public ActionResult CreateOrder()
        {
            ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 200, msg = "允许执行该操作的权限，操作成功！" };
            int _OrderId = DTRequest.GetQueryInt("OrderId");
            string action = DTRequest.GetQueryString("action");
            if (!ChkAdminLevels("OrderList", GetAddOrEdit(action)))
            {
                ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 400, msg = "您没有执行该操作的权限，操作失败！" };
                return View();
            }; //检查权限

            DeliveryManage.Model.Pro_Orders model = new DeliveryManage.Model.Pro_Orders();
            DeliveryManage.DAL.Pro_Orders dal = new DeliveryManage.DAL.Pro_Orders();
            if (_OrderId > 0)
            {
                model = dal.GetModelDetail(_OrderId);
            }
            ViewBag.AddOrEdit = action;

            #region 物流方式
            ListItemCollection wayitem = new ListItemCollection();
            wayitem.Add(new ListItem("请选择发货方式...", "-1"));
            wayitem.Add(new ListItem("京东-------京东物流", "0"));
            wayitem.Add(new ListItem("散酒-------散酒/定制酒(预付款≥20%)", "1"));
            wayitem.Add(new ListItem("存酒-------须全款，后续录单核销存酒", "2"));
            wayitem.Add(new ListItem("自提-------仓库自提", "3"));

            ViewData["DeliveryWayList"] = new SelectList(wayitem, "value", "text");
            #endregion

            return View(model);
        }

        [HttpPost]
        [ValidateInput(false)]
        public JsonResult SaveOrder(FormCollection collection)
        {
            try
            {
                bool result = false;
                #region 数据安防

                string action =string.IsNullOrEmpty(collection["AddOrEdit"])?"Add": collection["AddOrEdit"];
                if (!ChkAdminLevels("OrderList", GetAddOrEdit(action)))
                {
                    return Json(new ReturnMsgModel { status = false, msg = "您没有执行该操作的权限，操作失败！！" });
                }; //检查权限
                DeliveryManage.Model.Sys_User user = Session["session_admin_info"] as DeliveryManage.Model.Sys_User;
                DeliveryManage.DAL.Pro_ShopGoods dal = new DeliveryManage.DAL.Pro_ShopGoods();
                if ((action == "edit" && collection["Id"] == "0"))
                {
                    return Json(new ReturnMsgModel { status = false, msg = "保存失败！" });
                }
                if (string.IsNullOrEmpty(collection["OrderGoods"]))
                {
                    return Json(new ReturnMsgModel { status = false, msg = "请选择订单商品！" });
                }
                if (int.Parse(collection["DeliveryWay"]) == -1) 
                {
                    return Json(new ReturnMsgModel { status = false, msg = "请选择发货方式！" });
                }
                #endregion

                #region 保存数据
                DeliveryManage.DAL.Pro_Orders _OrdersDal = new DeliveryManage.DAL.Pro_Orders();
                DeliveryManage.DAL.Pro_OrderGoods _OrdersGoodsDal = new DeliveryManage.DAL.Pro_OrderGoods();
                if (action == "Add")
                {
                    #region 添加订单数据
                    DeliveryManage.Model.Pro_Orders _OrdersModel = new DeliveryManage.Model.Pro_Orders();
                    _OrdersModel.OrderNo = Utils.GetTimeStamp(DateTime.Now);//生成订单号
                    _OrdersModel.DeliveryWay = int.Parse(collection["DeliveryWay"]);
                    _OrdersModel.EmployeeId = user.Id;
                    _OrdersModel.Status = (int)DTEnums.EnumOrderState.NewCreateOrder;
                    _OrdersModel.CustomerName = collection["CustomerName"];
                    _OrdersModel.CustomerTel = collection["CustomerTel"];
                    _OrdersModel.CustomerAddress = collection["CustomerAddress"];
                    _OrdersModel.CustomerSex = bool.Parse(collection["CustomerSex"]);
                    _OrdersModel.OrderType =bool.Parse(collection["OrderType"]);
                    _OrdersModel.Remark = collection["Remark"];
                    _OrdersModel.Created = DateTime.Now;
                    _OrdersModel.Id = _OrdersDal.Add(_OrdersModel);
                    if (_OrdersModel.Id > 0)
                    {
                        //添加订单商品
                        DeliveryManage.Model.Pro_OrderGoods _OrdersGoodsModel = new DeliveryManage.Model.Pro_OrderGoods();
                        decimal TotalAmount = 0.00M;
                        string OrderGoods = collection["OrderGoods"].TrimEnd(',');
                        foreach (var item in OrderGoods.Split(','))
                        {
                            int GoodsId = int.Parse(item.Split('_')[0]);//产品Id
                            int Number = int.Parse(item.Split('_')[1]);//购买数量
                            decimal AddPrices = decimal.Parse(item.Split('_')[2]);//产品加价金额
                            decimal Freight = decimal.Parse(item.Split('_')[3]);//运费金额
                            decimal AdvancePay = decimal.Parse(item.Split('_')[4]);//预付款金额

                            DeliveryManage.DAL.Pro_ShopGoods _GoodsDal = new DeliveryManage.DAL.Pro_ShopGoods();
                            DeliveryManage.Model.Pro_ShopGoods _GoodsModel = _GoodsDal.GetModel(GoodsId);
                            if (_GoodsModel != null)
                            {
                                _OrdersGoodsModel.OrderId = _OrdersModel.Id;
                                _OrdersGoodsModel.GoodsId = _GoodsModel.Id;
                                _OrdersGoodsModel.GoodsName = _GoodsModel.Name;
                                _OrdersGoodsModel.IsActivity = _GoodsModel.Lable;
                                _OrdersGoodsModel.BuyNum = Number;
                                _OrdersGoodsModel.CalcSpec = Number * _GoodsModel.CalcSpec;
                                _OrdersGoodsModel.SpecNum = Number * _GoodsModel.SpecNum;
                                _OrdersGoodsModel.Price = _GoodsModel.Lable == false ? _GoodsModel.CounterPrices : _GoodsModel.ActivityPrices;
                                _OrdersGoodsModel.GoodsAmount = Number * _OrdersGoodsModel.Price;
                                _OrdersGoodsModel.AddPrice = AddPrices;
                                _OrdersGoodsModel.Freight = Freight;
                                _OrdersGoodsModel.AdvanceCharge = AdvancePay;
                                _OrdersGoodsModel.TotalAmount = _OrdersGoodsModel.GoodsAmount + AddPrices + Freight;//实际总金额=商品总价+商品加价+运费
                                _OrdersGoodsModel.InvoicingCharge = _OrdersGoodsModel.TotalAmount - AdvancePay;//代收尾款=实际总金额-预付款金额
                                TotalAmount += _OrdersGoodsModel.TotalAmount;//结算总金额

                                _OrdersGoodsDal.Add(_OrdersGoodsModel); //添加订单商品数据
                            }
                        }

                        //修改订单总金额
                        DeliveryManage.Model.Pro_Orders _NewOrdersModel = _OrdersDal.GetModel(_OrdersModel.Id);
                        if (_NewOrdersModel != null)
                        {
                            _NewOrdersModel.TotalAmount = TotalAmount;
                            if (_OrdersDal.Update(_NewOrdersModel))
                            {
                                result = true;
                            }
                        }
                    }
                    //添加消息队列
                    OrderMassageHandler.Instance.AddQueue(new NewOrderQueueInfo { NewOrderId= _OrdersModel.Id });
                    #endregion
                }
                else 
                {
                    #region 修改
                    DeliveryManage.Model.Pro_Orders _OrdersModel = new DeliveryManage.Model.Pro_Orders();
                    _OrdersModel = _OrdersDal.GetModel(int.Parse(collection["Id"]));
                    if (_OrdersModel != null)
                    {
                        _OrdersModel.DeliveryWay = int.Parse(collection["DeliveryWay"]);
                        _OrdersModel.Status = (int)DTEnums.EnumOrderState.NewCreateOrder;
                        _OrdersModel.CustomerName = collection["CustomerName"];
                        _OrdersModel.CustomerTel = collection["CustomerTel"];
                        _OrdersModel.CustomerAddress = collection["CustomerAddress"];
                        _OrdersModel.CustomerSex = bool.Parse(collection["CustomerSex"]); 
                        _OrdersModel.OrderType = bool.Parse(collection["OrderType"]);
                        _OrdersModel.Remark = collection["Remark"];
                        _OrdersModel.Created = DateTime.Now;
                        if (_OrdersDal.Update(_OrdersModel))
                        {
                            //清除订单商品
                            DbHelperSQL.ExecuteSql(string.Format("delete [dbo].[Pro_OrderGoods] where OrderId={0}", _OrdersModel.Id));

                            //添加订单商品
                            DeliveryManage.Model.Pro_OrderGoods _OrdersGoodsModel = new DeliveryManage.Model.Pro_OrderGoods();
                            decimal TotalAmount = 0.00M;
                            string OrderGoods = collection["OrderGoods"].TrimEnd(',');
                            foreach (var item in OrderGoods.Split(','))
                            {
                                int GoodsId = int.Parse(item.Split('_')[0]);//产品Id
                                int Number = int.Parse(item.Split('_')[1]);//购买数量
                                decimal AddPrices = decimal.Parse(item.Split('_')[2]);//产品加价金额
                                decimal Freight = decimal.Parse(item.Split('_')[3]);//运费金额
                                decimal AdvancePay = decimal.Parse(item.Split('_')[4]);//预付款金额

                                DeliveryManage.DAL.Pro_ShopGoods _GoodsDal = new DeliveryManage.DAL.Pro_ShopGoods();
                                DeliveryManage.Model.Pro_ShopGoods _GoodsModel = _GoodsDal.GetModel(GoodsId);
                                if (_GoodsModel != null)
                                {
                                    _OrdersGoodsModel.OrderId = _OrdersModel.Id;
                                    _OrdersGoodsModel.GoodsId = _GoodsModel.Id;
                                    _OrdersGoodsModel.GoodsName = _GoodsModel.Name;
                                    _OrdersGoodsModel.IsActivity = _GoodsModel.Lable;
                                    _OrdersGoodsModel.BuyNum = Number;
                                    _OrdersGoodsModel.CalcSpec = Number * _GoodsModel.CalcSpec;
                                    _OrdersGoodsModel.SpecNum = Number * _GoodsModel.SpecNum;
                                    _OrdersGoodsModel.Price = _GoodsModel.Lable == false ? _GoodsModel.CounterPrices : _GoodsModel.ActivityPrices;
                                    _OrdersGoodsModel.GoodsAmount = Number * _OrdersGoodsModel.Price;
                                    _OrdersGoodsModel.AddPrice = AddPrices;
                                    _OrdersGoodsModel.Freight = Freight;
                                    _OrdersGoodsModel.AdvanceCharge = AdvancePay;
                                    _OrdersGoodsModel.TotalAmount = _OrdersGoodsModel.GoodsAmount + AddPrices + Freight;//实际总金额=商品总价+商品加价+运费
                                    _OrdersGoodsModel.InvoicingCharge = _OrdersGoodsModel.TotalAmount - AdvancePay;//代收尾款=实际总金额-预付款金额
                                    TotalAmount += _OrdersGoodsModel.TotalAmount;//结算总金额

                                    _OrdersGoodsDal.Add(_OrdersGoodsModel); //添加订单商品数据
                                }
                            }

                            //修改订单总金额
                            DeliveryManage.Model.Pro_Orders _NewOrdersModel = _OrdersDal.GetModel(_OrdersModel.Id);
                            if (_NewOrdersModel != null)
                            {
                                _NewOrdersModel.TotalAmount = TotalAmount;
                                if (_OrdersDal.Update(_NewOrdersModel))
                                {
                                    result = true;
                                }
                            }
                        }
                    }
                    #endregion
                }
                #endregion
                if (result) 
                {
                    return Json(new ReturnMsgModel { status = true, msg = "下单成功！" });
                }
                return Json(new ReturnMsgModel { status = false, msg = "保存失败！" });
            }
            catch (Exception e)
            {
                var a = e.Message;
                return Json(new ReturnMsgModel { status = false, msg = "保存失败！" + a });
            }
        }
        #endregion

        #region 编辑订单
        //编辑订单
        public ActionResult EditOrder()
        {
            ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 200, msg = "允许执行该操作的权限，操作成功！" };
            int _OrderId = DTRequest.GetQueryInt("OrderId");
            string action = DTRequest.GetQueryString("action");
            if (!ChkAdminLevels("ReturnOrderList", GetAddOrEdit(action)))
            {
                ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 400, msg = "您没有执行该操作的权限，操作失败！" };
                return View();
            }; //检查权限

            DeliveryManage.Model.Pro_Orders model = new DeliveryManage.Model.Pro_Orders();
            DeliveryManage.DAL.Pro_Orders dal = new DeliveryManage.DAL.Pro_Orders();
            if (_OrderId > 0)
            {
                model = dal.GetModelDetail(_OrderId);
            }

            ViewBag.AddOrEdit = action;

            #region 物流方式
            ListItemCollection wayitem = new ListItemCollection();
            wayitem.Add(new ListItem("请选择发货方式...", "-1"));
            wayitem.Add(new ListItem("京东-------京东物流", "0"));
            wayitem.Add(new ListItem("散酒-------散酒/定制酒(预付款≥20%)", "1"));
            wayitem.Add(new ListItem("存酒-------须全款，后续录单核销存酒", "2"));
            wayitem.Add(new ListItem("自提-------仓库自提", "3"));

            ViewData["DeliveryWayList"] = new SelectList(wayitem, "value", "text");
            #endregion

            return View(model);
        }
        #endregion

        #region 获取订单商品
        [HttpPost]
        public JsonResult GetOrderGoods(int OrderId)
        {
            try
            {
                DeliveryManage.Model.Pro_Orders model = new DeliveryManage.Model.Pro_Orders();
                DeliveryManage.DAL.Pro_Orders dal = new DeliveryManage.DAL.Pro_Orders();
                if (OrderId > 0)
                {
                    model = dal.GetModelDetail(OrderId);
                    if (model!=null) 
                    {
                        return Json(new ReturnMsgModel { status = true,code=200, msg = "获取成功！",data= model.OrderGoods });
                    }
                }
                return Json(new ReturnMsgModel { status = false, code = 400, msg = "获取失败！" });
            }
            catch (Exception e)
            {
                var a = e.Message;
                return Json(new ReturnMsgModel { status = false, code = 400, msg = "获取失败！" + a });
            }

        }
        #endregion

        #region 选择商品套餐选择列表
        /// <summary>
        /// 商品套餐选择列表
        /// </summary>
        /// <returns></returns>
        public ActionResult SelectGoods()
        {
            ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 200, msg = "允许执行该操作的权限，操作成功！" };
            this.pageSize = GetPageSize(DTRequest.GetQueryInt("pageSize", 10), "pageSize");
            this.page = DTRequest.GetQueryInt("page", 1);

            ViewData["pageSize"] = this.pageSize;
            ViewData["page"] = this.page;
            #region 搜索
            string keywords = DTRequest.GetQueryString("keywords").Trim();
            string where = "IsShow=1 and Stock > 0";
            if (!string.IsNullOrEmpty(keywords))
            {
                //模糊查询
                if (keywords.IndexOf("*") >= 0)//判断字符串中是否包含字符串*号
                {
                    where += string.Format(" and (Name like '{0}' or Code like '{0}')", keywords.Replace("*", "%"));
                }
                else
                {
                    where += string.Format(" and (Name like '%{0}%' or Code like '%{0}%')", keywords);
                }
                ViewBag.Keyword = keywords;
            }

            #endregion
            List<DeliveryManage.Model.Pro_ShopGoods> list = new List<DeliveryManage.Model.Pro_ShopGoods>();
            DeliveryManage.DAL.Pro_ShopGoods dal = new DeliveryManage.DAL.Pro_ShopGoods();
            list = dal.GetQueryList(this.pageSize, this.page, where, "SortBy asc", out this.totalCount);
            ViewBag.ProductList = list;

            //绑定页码
            string pageUrl = Utils.CombUrlTxt("/Order/SelectGoods", "page={0}&pageSize={1}&keywords={2}", "__id__", pageSize.ToString(), keywords.ToString());
            ViewBag.PageInnerHtml = Utils.OutPageList(this.pageSize, this.page, this.totalCount, pageUrl, 8);
            return View();
        }
        #endregion

        #region 订单详情
        public ActionResult DetailOrder()
        {
            ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 200, msg = "允许执行该操作的权限，操作成功！" };
            int _OrderId = DTRequest.GetQueryInt("OrderId");
            if (!ChkAdminLevels("OrderList", DTEnums.ActionEnum.View.ToString()))
            {
                ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 400, msg = "您没有执行该操作的权限，操作失败！" };
                return View();
            }; //检查权限
            DeliveryManage.Model.Pro_Orders model = new DeliveryManage.Model.Pro_Orders();
            DeliveryManage.DAL.Pro_Orders dal = new DeliveryManage.DAL.Pro_Orders();
            if (_OrderId > 0)
            {
                model = dal.GetModelDetail(_OrderId);
            }

            #region 物流方式
            ListItemCollection wayitem = new ListItemCollection();
            wayitem.Add(new ListItem("请选择发货方式...", "-1"));
            wayitem.Add(new ListItem("京东-------京东物流", "0"));
            wayitem.Add(new ListItem("散酒-------散酒/定制酒(预付款≥20%)", "1"));
            wayitem.Add(new ListItem("存酒-------须全款，后续录单核销存酒", "2"));
            wayitem.Add(new ListItem("自提-------仓库自提", "3"));

            ViewData["DeliveryWayList"] = new SelectList(wayitem, "value", "text");
            #endregion

            return View(model);
        }
        #endregion

        #region 删除订单记录

        public ActionResult DeleteOrder()
        {
            ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 200, msg = "允许执行该操作的权限，操作成功！" };
            if (!ChkAdminLevels("OrderList", DTEnums.ActionEnum.Delete.ToString()))
            {
                ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 400, msg = "您没有执行该操作的权限，操作失败！" };
                return View();
            }; //检查权限

            return View();
        }

        #endregion

        #region 待审核订单
        /// <summary>
        /// 待审核列表
        /// </summary>
        /// <returns></returns>
        public ActionResult UnAuditOrderList()
        {
            ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 200, msg = "允许执行该操作的权限，操作成功！" };
            if (!ChkAdminLevels("UnAuditOrderList", DTEnums.ActionEnum.View.ToString()))
            {
                ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 400, msg = "您没有执行该操作的权限，操作失败！" };
                return View();
            }; //检查权限
            #region 搜索
            DeliveryManage.Model.Sys_User user = Session["session_admin_info"] as DeliveryManage.Model.Sys_User;
            this.pageSize = GetPageSize(DTRequest.GetQueryInt("pageSize", 10), "pageSize");
            this.page = DTRequest.GetQueryInt("page", 1);

            ViewData["pageSize"] = this.pageSize;
            ViewData["page"] = this.page;

            DeliveryManage.DAL.Sys_UserRelation userRelationDal = new DeliveryManage.DAL.Sys_UserRelation();
            string myLower = userRelationDal.GetMyLowerList(user.Id);
            string where = string.Format(" EmployeeId in({0}) and Status = {1}", myLower, (int)DTEnums.EnumOrderState.NewCreateOrder);
            string keywords = DTRequest.GetQueryString("keywords").Trim();
            if (!string.IsNullOrEmpty(keywords))
            {
                //模糊查询
                if (keywords.IndexOf("*") >= 0)//判断字符串中是否包含字符串*号
                {
                    where += string.Format(" and (OrderNo like '{0}' or CustomerName like '{0}' or CustomerTel like '{0}')", keywords.Replace("*", "%"));
                }
                else
                {
                    where += string.Format(" and (OrderNo like '%{0}%' or CustomerName like '%{0}%' or CustomerTel like '%{0}%')", keywords);
                }
                ViewBag.Keyword = keywords;
            }

            #endregion
            List<DeliveryManage.Model.Pro_Orders> list = new List<DeliveryManage.Model.Pro_Orders>();
            DeliveryManage.DAL.Pro_Orders dal = new DeliveryManage.DAL.Pro_Orders();
            list = dal.GetQueryList(this.pageSize, this.page, where, "Id Desc", out this.totalCount);

            ViewBag.OrderList = list;

            //绑定页码
            string pageUrl = Utils.CombUrlTxt("/Order/UnAuditOrderList", "page={0}&pageSize={1}&keywords={2}", "__id__", pageSize.ToString(), keywords.ToString());
            ViewBag.PageInnerHtml = Utils.OutPageList(this.pageSize, this.page, this.totalCount, pageUrl, 8);

            #region 物流方式
            ListItemCollection wayitem = new ListItemCollection();
            wayitem.Add(new ListItem("请选择发货方式...", "-1"));
            wayitem.Add(new ListItem("京东", "0"));
            wayitem.Add(new ListItem("散酒", "1"));
            wayitem.Add(new ListItem("存酒", "2"));
            wayitem.Add(new ListItem("自提", "3"));

            ViewData["DeliveryWayList"] = new SelectList(wayitem, "value", "text");

            Dictionary<int, string> dicDeliveryWay = new Dictionary<int, string>();
            dicDeliveryWay.Add(0, "京东");
            dicDeliveryWay.Add(1, "散酒");
            dicDeliveryWay.Add(2, "存酒");
            dicDeliveryWay.Add(3, "自提");
            ViewData["dicDeliveryWay"] = dicDeliveryWay;
            #endregion

            #region 订单状态
            Dictionary<int, string> dicStatus = new Dictionary<int, string>();
            List<EnumEntity> enumList = DTEnums.EnumToList<DTEnums.EnumOrderState>();
            foreach (var item in enumList)
            {
                dicStatus.Add(item.PrameKey, item.Describe);
            }
            ViewData["dicStatus"] = dicStatus;

            #endregion
            return View();
        }

        /// <summary>
        /// 订单审核
        /// </summary>
        /// <returns></returns>
        public ActionResult AuditOrderDetail()
        {
            ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 200, msg = "允许执行该操作的权限，操作成功！" };
            int _OrderId = DTRequest.GetQueryInt("OrderId");
            if (!ChkAdminLevels("UnAuditOrderList", DTEnums.ActionEnum.Audit.ToString()))
            {
                ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 400, msg = "您没有执行该操作的权限，操作失败！" };
                return View();
            }; //检查权限
            DeliveryManage.Model.Pro_Orders model = new DeliveryManage.Model.Pro_Orders();
            DeliveryManage.DAL.Pro_Orders dal = new DeliveryManage.DAL.Pro_Orders();
            if (_OrderId > 0)
            {
                model = dal.GetModelDetail(_OrderId);
            }

            #region 物流方式
            ListItemCollection wayitem = new ListItemCollection();
            wayitem.Add(new ListItem("请选择发货方式...", "-1"));
            wayitem.Add(new ListItem("京东-------京东物流", "0"));
            wayitem.Add(new ListItem("散酒-------散酒/定制酒(预付款≥20%)", "1"));
            wayitem.Add(new ListItem("存酒-------须全款，后续录单核销存酒", "2"));
            wayitem.Add(new ListItem("自提-------仓库自提", "3"));

            ViewData["DeliveryWayList"] = new SelectList(wayitem, "value", "text");
            #endregion

            return View(model);
        }

        [HttpPost]
        public JsonResult OrderAuditPost()
        {
            if (!ChkAdminLevels("UnAuditOrderList", DTEnums.ActionEnum.Audit.ToString()))
            {
                return Json(new ReturnMsgModel { status = false, code = 400, msg = "您没有执行该操作的权限，操作失败！！" });
            }; //检查权限

            DeliveryManage.Model.Sys_User user = Session["session_admin_info"] as DeliveryManage.Model.Sys_User;
            int _id = DTRequest.GetFormInt("id");
            bool IsAuditOk =bool.Parse(DTRequest.GetFormString("result"));
            DeliveryManage.DAL.Pro_Orders dal = new DeliveryManage.DAL.Pro_Orders();
            DeliveryManage.Model.Pro_Orders model = dal.GetModel(_id);
            if (model != null && model.Id > 0) {
                model.Status = (int)(IsAuditOk ? DTEnums.EnumOrderState.AuditSuccess : DTEnums.EnumOrderState.AuditFail);
                dal.Update(model);
            }
            return Json(new ReturnMsgModel { code = 200, msg = "操作成功" });
        }
        #endregion

        #region 已审核订单列表
        /// <summary>
        /// 待审核列表
        /// </summary>
        /// <returns></returns>
        public ActionResult AuditOrderList()
        {
            ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 200, msg = "允许执行该操作的权限，操作成功！" };
            if (!ChkAdminLevels("AuditOrderList", DTEnums.ActionEnum.View.ToString()))
            {
                ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 400, msg = "您没有执行该操作的权限，操作失败！" };
                return View();
            }; //检查权限
            #region 搜索
            DeliveryManage.Model.Sys_User user = Session["session_admin_info"] as DeliveryManage.Model.Sys_User;
            this.pageSize = GetPageSize(DTRequest.GetQueryInt("pageSize", 10), "pageSize");
            this.page = DTRequest.GetQueryInt("page", 1);

            ViewData["pageSize"] = this.pageSize;
            ViewData["page"] = this.page;
            DeliveryManage.DAL.Sys_UserRelation userRelationDal = new DeliveryManage.DAL.Sys_UserRelation();
            string myLower = userRelationDal.GetMyLowerList(user.Id);

            string where = string.Format(" EmployeeId in({0}) and Status in({1},{2},{3},{4})", myLower,(int)DTEnums.EnumOrderState.AuditSuccess, (int)DTEnums.EnumOrderState.ApplyReback, (int)DTEnums.EnumOrderState.ReBackMoney, (int)DTEnums.EnumOrderState.FinishOrder);
            string keywords = DTRequest.GetQueryString("keywords").Trim();
            if (!string.IsNullOrEmpty(keywords))
            {
                //模糊查询
                if (keywords.IndexOf("*") >= 0)//判断字符串中是否包含字符串*号
                {
                    where += string.Format(" and (OrderNo like '{0}' or CustomerName like '{0}' or CustomerTel like '{0}')", keywords.Replace("*", "%"));
                }
                else
                {
                    where += string.Format(" and (OrderNo like '%{0}%' or CustomerName like '%{0}%' or CustomerTel like '%{0}%')", keywords);
                }
                ViewBag.Keyword = keywords;
            }

            #endregion
            List<DeliveryManage.Model.Pro_Orders> list = new List<DeliveryManage.Model.Pro_Orders>();
            DeliveryManage.DAL.Pro_Orders dal = new DeliveryManage.DAL.Pro_Orders();
            list = dal.GetQueryList(this.pageSize, this.page, where, "Id Desc", out this.totalCount);

            ViewBag.OrderList = list;

            //绑定页码
            string pageUrl = Utils.CombUrlTxt("/Order/AuditOrderList", "page={0}&pageSize={1}&keywords={2}", "__id__", pageSize.ToString(), keywords.ToString());
            ViewBag.PageInnerHtml = Utils.OutPageList(this.pageSize, this.page, this.totalCount, pageUrl, 8);

            #region 物流方式
            ListItemCollection wayitem = new ListItemCollection();
            wayitem.Add(new ListItem("请选择发货方式...", "-1"));
            wayitem.Add(new ListItem("京东", "0"));
            wayitem.Add(new ListItem("散酒", "1"));
            wayitem.Add(new ListItem("存酒", "2"));
            wayitem.Add(new ListItem("自提", "3"));

            ViewData["DeliveryWayList"] = new SelectList(wayitem, "value", "text");

            Dictionary<int, string> dicDeliveryWay = new Dictionary<int, string>();
            dicDeliveryWay.Add(0, "京东");
            dicDeliveryWay.Add(1, "散酒");
            dicDeliveryWay.Add(2, "存酒");
            dicDeliveryWay.Add(3, "自提");
            ViewData["dicDeliveryWay"] = dicDeliveryWay;
            #endregion

            #region 订单状态
            Dictionary<int, string> dicStatus = new Dictionary<int, string>();
            List<EnumEntity> enumList = DTEnums.EnumToList<DTEnums.EnumOrderState>();
            foreach (var item in enumList)
            {
                dicStatus.Add(item.PrameKey, item.Describe);
            }
            ViewData["dicStatus"] = dicStatus;

            #endregion
            return View();
        }
        #endregion

        #region 已驳回订单
        /// <summary>
        /// 已驳回订单列表
        /// </summary>
        /// <returns></returns>
        public ActionResult ReturnOrderList()
        {
            ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 200, msg = "允许执行该操作的权限，操作成功！" };
            if (!ChkAdminLevels("ReturnOrderList", DTEnums.ActionEnum.View.ToString()))
            {
                ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 400, msg = "您没有执行该操作的权限，操作失败！" };
                return View();
            }; //检查权限
            #region 搜索
            DeliveryManage.Model.Sys_User user = Session["session_admin_info"] as DeliveryManage.Model.Sys_User;
            DeliveryManage.DAL.Sys_UserRelation userRelationDal = new DeliveryManage.DAL.Sys_UserRelation();
            this.pageSize = GetPageSize(DTRequest.GetQueryInt("pageSize", 10), "pageSize");
            this.page = DTRequest.GetQueryInt("page", 1);

            ViewData["pageSize"] = this.pageSize;
            ViewData["page"] = this.page;
            string myLower = userRelationDal.GetMyLowerList(user.Id);
            string where = string.Format("EmployeeId in ({0}) and Status = {1}", myLower,(int)DTEnums.EnumOrderState.AuditFail);

            string keywords = DTRequest.GetQueryString("keywords").Trim();
            if (!string.IsNullOrEmpty(keywords))
            {
                //模糊查询
                if (keywords.IndexOf("*") >= 0)//判断字符串中是否包含字符串*号
                {
                    where += string.Format(" and (OrderNo like '{0}' or CustomerName like '{0}' or CustomerTel like '{0}')", keywords.Replace("*", "%"));
                }
                else
                {
                    where += string.Format(" and (OrderNo like '%{0}%' or CustomerName like '%{0}%' or CustomerTel like '%{0}%')", keywords);
                }
                ViewBag.Keyword = keywords;
            }

            #endregion
            List<DeliveryManage.Model.Pro_Orders> list = new List<DeliveryManage.Model.Pro_Orders>();
            DeliveryManage.DAL.Pro_Orders dal = new DeliveryManage.DAL.Pro_Orders();
            list = dal.GetQueryList(this.pageSize, this.page, where, "Id Desc", out this.totalCount);


            ViewBag.OrderList = list;

            //绑定页码
            string pageUrl = Utils.CombUrlTxt("/Order/ReturnOrderList", "page={0}&pageSize={1}&keywords={2}", "__id__", pageSize.ToString(), keywords.ToString());
            ViewBag.PageInnerHtml = Utils.OutPageList(this.pageSize, this.page, this.totalCount, pageUrl, 8);


            #region 物流方式
            ListItemCollection wayitem = new ListItemCollection();
            wayitem.Add(new ListItem("请选择发货方式...", "-1"));
            wayitem.Add(new ListItem("京东", "0"));
            wayitem.Add(new ListItem("散酒", "1"));
            wayitem.Add(new ListItem("存酒", "2"));
            wayitem.Add(new ListItem("自提", "3"));

            ViewData["DeliveryWayList"] = new SelectList(wayitem, "value", "text");

            Dictionary<int, string> dicDeliveryWay = new Dictionary<int, string>();
            dicDeliveryWay.Add(0, "京东");
            dicDeliveryWay.Add(1, "散酒");
            dicDeliveryWay.Add(2, "存酒");
            dicDeliveryWay.Add(3, "自提");
            ViewData["dicDeliveryWay"] = dicDeliveryWay;
            #endregion

            #region 订单状态
            Dictionary<int, string> dicStatus = new Dictionary<int, string>();
            List<EnumEntity> enumList = DTEnums.EnumToList<DTEnums.EnumOrderState>();
            foreach (var item in enumList)
            {
                dicStatus.Add(item.PrameKey, item.Describe);
            }
            ViewData["dicStatus"] = dicStatus;

            #endregion
            return View();
        }

        /// <summary>
        /// 更新订单内容重新提交
        /// </summary>
        /// <returns></returns>
        public ActionResult OrderUpdate()
        {
            ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 200, msg = "允许执行该操作的权限，操作成功！" };
            int _OrderId = DTRequest.GetQueryInt("OrderId");
            string action = DTRequest.GetQueryString("action");
            if (!ChkAdminLevels("OrderList", GetAddOrEdit(action)))
            {
                ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 400, msg = "您没有执行该操作的权限，操作失败！" };
                return View();
            }; //检查权限

            DeliveryManage.Model.Pro_Orders model = new DeliveryManage.Model.Pro_Orders();
            DeliveryManage.DAL.Pro_Orders dal = new DeliveryManage.DAL.Pro_Orders();
            if (_OrderId > 0)
            {
                model = dal.GetModelDetail(_OrderId);
            }
            ViewBag.AddOrEdit = action;
            return View(model);
        }
        #endregion

        #region 修改订单状态
        public ActionResult EditOrderStatus()
        {
            ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 200, msg = "允许执行该操作的权限，操作成功！" };
            int _OrderId = DTRequest.GetQueryInt("OrderId");
            string action = DTRequest.GetQueryString("action");
            if (!ChkAdminLevels("ReturnOrderList", GetAddOrEdit(action)))
            {
                ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 400, msg = "您没有执行该操作的权限，操作失败！" };
                return View();
            }; //检查权限
            DeliveryManage.Model.Pro_Orders model = new DeliveryManage.Model.Pro_Orders();
            DeliveryManage.DAL.Pro_Orders dal = new DeliveryManage.DAL.Pro_Orders();
            if (_OrderId > 0)
            {
                model = dal.GetModelDetail(_OrderId);
            }

            #region 订单状态

            List<EnumEntity> enumList = DTEnums.EnumToList<DTEnums.EnumOrderState>();
            ListItemCollection Statusitem = new ListItemCollection();
            Statusitem.Add(new ListItem("全部...", "-1"));
            foreach (var item in enumList)
            {
                Statusitem.Add(new ListItem(item.Describe, item.PrameKey.ToString()));
            }
            ViewData["StatusList"] = new SelectList(Statusitem, "value", "text");

            #endregion


            ViewBag.AddOrEdit = action;
            return View(model);
        }
        /// <summary>
        /// 编辑订单状态
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public JsonResult UpdateOrderStatus(FormCollection collection)
        {
            try
            {
                bool result = false;
                #region 数据安防

                string action = collection["AddOrEdit"];
                if (!ChkAdminLevels("AuditOrderList", GetAddOrEdit(action)))
                {
                    return Json(new ReturnMsgModel { status = false, msg = "您没有执行该操作的权限，操作失败！！" });
                }; //检查权限
                DeliveryManage.Model.Sys_User user = Session["session_admin_info"] as DeliveryManage.Model.Sys_User;
                DeliveryManage.DAL.Pro_ShopGoods dal = new DeliveryManage.DAL.Pro_ShopGoods();
                if ((action == "edit" && collection["Id"] == "0"))
                {
                    return Json(new ReturnMsgModel { status = false, msg = "保存失败！" });
                }
                if (int.Parse(collection["Status"]) == -1) 
                {
                    return Json(new ReturnMsgModel { status = false, msg = "请选择订单状态！" });
                }
                #endregion

                #region 保存数据
                DeliveryManage.DAL.Pro_Orders _OrdersDal = new DeliveryManage.DAL.Pro_Orders();
                DeliveryManage.Model.Pro_Orders _OrdersModel = new DeliveryManage.Model.Pro_Orders();
                _OrdersModel = _OrdersDal.GetModel(int.Parse(collection["Id"]));
                if (_OrdersModel != null) 
                {
                    _OrdersModel.Status= int.Parse(collection["Status"]);
                    _OrdersModel.Remark = collection["Remark"];
                    if (_OrdersDal.Update(_OrdersModel)) 
                    {
                        result = true;
                    }
                }
                #endregion
                if (result)
                {
                    return Json(new ReturnMsgModel { status = true, msg = "保存成功！" });
                }
                return Json(new ReturnMsgModel { status = false, msg = "保存失败！" });
            }
            catch (Exception e)
            {
                var a = e.Message;
                return Json(new ReturnMsgModel { status = false, msg = "保存失败！" + a });
            }
        }
        #endregion
    }
}